/**
 * 
 */
package info.niwota.home.web;

import instant.openvfs.home.Debug;

import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;

import jvs.vfs.ContentTypes;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import x.java.io.File;
import android.content.Context;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

/**
 * /content/info.niwota.home/jsonp/jvsfile/listFile?path=" + encodedPath;
 * 
 * @author qiangli
 * 
 */
public class JvsFileObject {
	private static final SimpleDateFormat df = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm");

	public static final String NAME = "jvsfile";

	private static final String TAG = "JvsFileObject";

	public JvsFileObject(Context ctx) {
	}

	public Object listFile(JSONObject param, Uri uri) throws JSONException {
		if (Debug.DEBUG) {
			Log.d(TAG, "listFile uri: " + uri);
		}
		final long starttime = System.currentTimeMillis();
		String path = uri.getQueryParameter("path");
		path = (TextUtils.isEmpty(path) ? "/" : path);
		x.java.io.File file = new x.java.io.File("v:" + path);

		final int view = getView(uri);
		final x.java.io.File[] files = (file == null ? new x.java.io.File[0]
				: file.listFiles());
		final int total = (files == null ? 0 : files.length);
		final boolean isEmpty = (total == 0);
		final boolean canRead = (file.canRead());
		JSONArray list = new JSONArray();
		if (!isEmpty) {
			for (int i = 0; i < files.length; i++) {
				list.put(toJSONObject(files[i]));
			}
		}

		final long now = System.currentTimeMillis();
		JSONObject json = new JSONObject();
		json.put("elapsed", "" + (now - starttime));
		json.put("path", path);
		json.put("view", view);
		json.put("canRead", canRead);
		json.put("list", list);
		json.put("total", total);
		json.put("isEmpty", isEmpty);
		//
		if (Debug.DEBUG) {
			Log.d(TAG, "listFile returning file: " + file);
		}
		return json;
	}

	public static String scan(String cookies, String key) {
		if (TextUtils.isEmpty(cookies)) {
			return null;
		}
		final String[] sa = cookies.split(";");
		final String key_ = key + "=";
		for (int i = 0; i < sa.length; i++) {
			String sai = sa[i].trim();
			if (sai.startsWith(key_)) {
				return sai.substring(key.length() + 1);
			}
		}
		return null;
	}

	public static int getView(Uri uri) {
		try {
			String s = uri.getQueryParameter("view");
			if (s == null) {
				String data = uri.getQueryParameter("data");
				s = scan(data, "view");
			}
			if (s == null) {
				// cookies passed as query param
				String cookies = uri.getQueryParameter("cookies");
				s = scan(cookies, "view");
			}
			if (s == null) {
				return 0;
			}
			int view = Integer.parseInt(s);
			return (view < 0 || view > 2 ? 0 : view);
		} catch (Exception e) {
			// e.printStackTrace();
		}
		return 0;
	}

	private static JSONObject toJSONObject(File file) throws JSONException {
		final JSONObject json = new JSONObject();
		json.put("path", file.getPath());
		json.put("name", file.getName());
		json.put("displayName", file.getDisplayName());
		json.put("lastModified", file.lastModified());
		json.put("date", df.format(file.lastModified()));
		if (file.isDirectory()) {
			json.put("isFile", false);
			json.put("type", "");
		} else {
			json.put("isFile", true);
			json.put("length", file.length());
			json.put("size", File.formatSize(file.length()));
			json.put("type", file.getContentType());
			//
			String icon = getIcon(file);
			json.put("icon", icon);
		}
		json.put("canRead", file.canRead());
		json.put("canWrite", file.canWrite());
		json.put("canExecute", file.canExecute());
		return json;
	}

	private static String getIcon(File file) {
		try {
			String type = file.getContentType();
			if (ContentTypes.APP_URI.equals(type)) {
				URL favicon = new URL(file.toRealURI().toURL(), "/favicon.ico");
				return favicon.toString();
			} else if (ContentTypes.APP_ANDROID.equals(type)) {
				return file.getIcon().toString();
			} 
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		return null;
	}

}
